import router, { asyncRoutes } from '@/router'
import { defineStore } from 'pinia'

import type { RouteRecordRaw } from 'vue-router'

function clearAsyncRoutes(routes: RouteRecordRaw[]) {
  routes.forEach((route) => {
    if (route.children) {
      clearAsyncRoutes(route.children)
    }
    router.hasRoute(route.name as symbol) && router.removeRoute(route.name as symbol)
  })
}

interface userInfo {
  roles: string[]
}

export const useUserStore = defineStore('user', () => {
  const user: userInfo = {
    roles: []
  }
  function changeRoles(roles: string[]) {
    return new Promise<string[]>((resolve) => {
      if (!Array.isArray(roles)) {
        roles = [roles]
      }
      user.roles = roles
      clearAsyncRoutes(asyncRoutes)
      resolve(roles)
    })
  }

  return {
    user,
    changeRoles
  }
})

// // 非setup
// export function useUserStoreHook() {
//   return useUserStore(store)
// }
